﻿using aspNetCURD.Database;
using aspNetCURD.Models;
using Microsoft.EntityFrameworkCore.Query;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;

namespace aspNetCURD.Services
{
    public class StudentRepository:IStudentRepository
    {
        private readonly AppDbContext _context;
        public StudentRepository(AppDbContext context)
        {
            _context = context;
        }

        public IEnumerable<Student> GetStudents(string keyword,int pageIndex, int pageSize)
        {
            int skip = (pageIndex - 1)*pageSize;
            if (!string.IsNullOrEmpty(keyword))
            {
                keyword = keyword.Trim();
            }
            //IQueryable<Student> result = _context.student;
            if (!string.IsNullOrEmpty(keyword))
            {
                return _context.student.Where(
                    n => n.sno.Contains(keyword) ||
                    n.sname.Contains(keyword) ||
                    n.ssex.Contains(keyword) ||
                    n.specialty.Contains(keyword) ||
                    n.grade.Contains(keyword)
                ).Skip(skip)
                    .Take(pageSize).ToList();
            }
            else
            {
                return _context.student
                    .Skip(skip)
                    .Take(pageSize).ToList();
            }
        }

        public Student GetStudent(string sno)
        {
            return _context.student.Where(n => n.sno == sno.Trim()).FirstOrDefault();
        }

        public int GetStudentsCount(string keyword)
        {
            if (!string.IsNullOrEmpty(keyword))
            {
                keyword = keyword.Trim();
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                return _context.student.Where(
                    n => n.sno.Contains(keyword) ||
                    n.sname.Contains(keyword) ||
                    n.ssex.Contains(keyword) ||
                    n.specialty.Contains(keyword) ||
                    n.grade.Contains(keyword)
                ).ToList().Count();
            }
            else
            {
                return _context.student.ToList().Count();
            }
        }

        public void AddStudent(Student student)
        {
            _context.student.Add(student);
        }

        public bool StudentEmpty(string sno)
        {
            return _context.student.All(n => n.sno == sno.Trim());
        }

        public bool Save()
        {
            return (_context.SaveChanges() >= 0);
        }
    }
}
